Ext.ns('journal.home');

journal.home.EntryExplorerHandler = function() {
    // do NOT access DOM from here; elements don't exist yet
    // private variables
    // private functions
    /**
     * Checks whether the passed node is currently stored in recent item list state.
     * 
     * @private
     */
    var isInRecent = function(node) {
        return journal.StateService.contains(journal.StateService.ST_RECENTLIST, node.getPath() + '|' + node.text);
    };

    /**
     * Note: node path will be replaced by id, and should later be replaced by the correct path after move.
     * 
     * @private
     */
    var getStateObj = function(node) {
        var nodeIsLoaded = journal.StateService.contains(journal.StateService.ST_TAB, node.getPath());
        var nodeIsExpanded = journal.StateService.contains(journal.StateService.ST_TREE, node.getPath());
        var nodeIsRecent = node.isLeaf() && isInRecent(node);

        if (nodeIsRecent) {
            journal.home.MainHandler.removeRecentFileItem(node);
        }
        if (nodeIsLoaded) {
            journal.StateService.remove(journal.StateService.ST_TAB, node.getPath());
            journal.StateService.replace(journal.StateService.ST_TABORDER, node.getPath(), node.id);
        }
        if (nodeIsExpanded) {
            journal.StateService.remove(journal.StateService.ST_TREE, node.getPath());
        }

        return {
            'id' : node.id,
            'isRecent' : nodeIsRecent,
            'isLoaded' : nodeIsLoaded,
            'isExpanded' : nodeIsExpanded
        };
    };

    // public space
    return {

        /**
         * Deletes the currently selected node.
         */
        deleteNodeHandler : function(node) {
            Ext.Msg.show({
                icon : Ext.MessageBox.QUESTION,
                buttons : Ext.Msg.YESNO,
                title : 'Delete Node',
                msg : 'Are you sure you want to delete <a class="keyword">' + node.text + '</a></b>',
                fn : function(btn) {
                    if (btn == 'yes') {
                        var conn = new Ext.data.Connection();
                        var urlParam = node.isLeaf() ? 'deleteEntry' : 'deleteNode';
                        conn.request({
                            url : 'home?action=' + urlParam,
                            method : 'POST',
                            params : {
                                branchId : node.id,
                                entryId : node.id
                            },
                            success : function(respParam) {
                                var respObj = Ext.util.JSON.decode(respParam.responseText);
                                if (respObj.success) {
                                    // Remove from state
                                    if (node.isLeaf()) {
                                        journal.StateService.remove(journal.StateService.ST_TAB, node.getPath());
                                        journal.StateService.remove(journal.StateService.ST_TABORDER, node.getPath());
                                        journal.home.MainHandler.removeRecentFileItem(node);
                                    } else {
                                        while (node.firstChild) {
                                            var childNode = node.firstChild;
                                            journal.home.MainHandler.removeRecentFileItem(childNode);
                                            node.removeChild(childNode);
                                        }
                                        journal.StateService.remove(journal.StateService.ST_TREE, node.getPath());

                                    }
                                    node.parentNode.removeChild(node);
                                    journal.home.MainHandler.fixRecentItemIndex();

                                    var targetTab = journal.home.Main.editorPanel.items.find(function(item) {
                                        //First condition needed when iter points at a search tab.
                                        return item.node != null && item.node.id == node.id;
                                    });
                                    if (targetTab != null) {
                                        targetTab.destroy();
                                    }
                                } else {
                                    journal.Utility.doStandardError(respObj);
                                }
                            }.createDelegate(this),
                            failure : function(responseObject) {
                                Ext.Msg.alert('Status',
                                        'Unable to contact server at this time. Please try again later.');
                            }
                        });
                    }
                }
            });
        },

        /**
         * Adds new branch to the given node.
         */
        addFolderHandler : function(targetNode) {
            targetNode.expand();
            Ext.Msg.prompt('Add Branch to <a class="keyword">[' + targetNode.text + ']</a>', 'Branch Name', function(
                    btn, text) {
                if (btn == 'ok') {
                    if (text == '' || text == 'Root') {
                        var errorMsg = text == '' ? 'Branch name cannot be empty'
                                : 'Branch cannot be named <b>Root</b>';
                        Ext.Msg.show({
                            icon : Ext.MessageBox.ERROR,
                            buttons : Ext.Msg.OK,
                            title : 'Validation Error',
                            msg : errorMsg
                        });
                        return;
                    }
                    new Ext.data.Connection().request({
                        url : 'home?action=addBranch',
                        method : 'POST',
                        params : {
                            parentId : targetNode.id,
                            branchName : text
                        },
                        success : function(respParam) {
                            var respObj = Ext.util.JSON.decode(respParam.responseText);
                            if (respObj.success == true) {
                                var newNode = new Ext.tree.TreeNode({
                                    id : 'b-' + respObj.id,
                                    text : respObj.branchName,
                                    leaf : false,
                                    expandable : true
                                });
                                targetNode.appendChild(newNode);
                                targetNode.expand();
                                newNode.select();
                                newNode.expand();
                            } else {
                                journal.Utility.doStandardError(respObj);
                            }
                        },
                        failure : function(responseObject) {
                            Ext.Msg.alert('Status', 'Unable to contact server at this time. Please try again later.');
                        }
                    });
                }
            });
        },
        /**
         * 
         */
        beforeMoveNodeHandler : function(scope, param) {
            if (param.newParent.text == 'Root' && param.node.isLeaf()) {
                return false;
            } else if (param.oldParent != param.newParent) {

                scope.nodesState = new Array();
                if (!param.node.isLeaf()) {
                    param.node.cascade(function(n) {
                        scope.nodesState.push(getStateObj(n));
                    }.createDelegate(scope));
                }

                Ext.Ajax.request({
                    url : 'home?action=moveNode',
                    params : {
                        nodeId : param.node.id,
                        parentId : param.newParent.id,
                        isLeaf : param.node.isLeaf()
                    },
                    success : function(response, opts) {

                        var respObj = Ext.util.JSON.decode(response.responseText);
                        if (respObj.success) {
                        } else {
                            journal.Utility.doStandardError(respObj);
                            oldParent.appendChild(param.node);
                            oldParent.expand();
                        }

                        for ( var i = 0; i < this.nodesState.length; i++) {
                            var movedNode = this.getNodeById(this.nodesState[i].id);
                            if (this.nodesState[i].isRecent) {
                                journal.home.MainHandler.addRecentFileItem(movedNode);
                            }
                            if (this.nodesState[i].isLoaded) {
                                journal.StateService.add(journal.StateService.ST_TAB, movedNode.getPath());
                                journal.StateService.replace(journal.StateService.ST_TABORDER, this.nodesState[i].id,
                                        movedNode.getPath());
                            }
                            if (this.nodesState[i].isExpanded) {
                                journal.StateService.add(journal.StateService.ST_TREE, movedNode.getPath());
                            }
                        }
                    }.createDelegate(scope),
                    failure : function(response, opts) {
                        // Note: Will arrive here on System Error only.
                    }
                });
            }
        }
    };
}(); // end of app

// end of file

